package com.oa.ht.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.ht.entity.*;
import com.oa.ht.service.ContractConditionService;
import com.oa.ht.service.ContractPaymentInvoiceService;
import com.oa.ht.service.ContractPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/**/oa/ht/contractPayment")
@Api(tags = {"ht_contract_payment-操作接口"})
public class ContractPaymentController {

    static Logger logger = LoggerFactory.getLogger(ContractPaymentController.class);

    @Autowired
    private ContractPaymentService contractPaymentService;

    @Autowired
    private ContractConditionService contractConditionService;

    @Autowired
    ContractPaymentInvoiceService contractPaymentInvoiceService;

    @ApiOperation(value = "ht_contract_payment-查询列表", notes = " ")
    @ApiEntityParams(ContractPayment.class)
    @ApiResponses({@ApiResponse(code = 200, response = ContractPayment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listContractPayment(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        QueryWrapper<ContractPayment> qw = QueryTools.initQueryWrapper(ContractPayment.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = contractPaymentService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "ht_contract_payment-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractPayment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addContractPayment(@RequestBody ContractPaymentVo contractPayment) {
        if (contractPayment.getPayAmount() == null || contractPayment.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("payAmount-is-zero", "付款金额不能为空，并且必须大于0");
        }
        if (StringUtils.isEmpty(contractPayment.getId())) {
            contractPayment.setId(contractPaymentService.createKey("id"));
        } else {
            ContractPayment contractPaymentQuery = new ContractPayment(contractPayment.getId());
            if (contractPaymentService.countByWhere(contractPaymentQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        if (!StringUtils.hasText(contractPayment.getConditionId())) {
            return Result.error("conditionId-is-null", "conditionId不能为空");
        }
        ContractCondition contractCondition = new ContractCondition(contractPayment.getConditionId());
        contractCondition = this.contractConditionService.selectOneObject(contractCondition);
        if (contractCondition == null) {
            return Result.error("condition-not-exists", "款项不存在");
        } else {
            if (contractCondition.getFinishAmount() == null) {
                contractCondition.setFinishAmount(BigDecimal.ZERO);
            }
            if ("2".equals(contractCondition.getConditionStatus())) {
                return Result.error("all-is-finish", "所有应付金额已完成，不能再付款");
            }
            if (contractCondition.getConditionAmount().compareTo(contractCondition.getFinishAmount()) <= 0) {
                return Result.error("all-is-finish", "所有应付金额已完成，不能再付款");
            }
            if (contractCondition.getConditionAmount().subtract(contractCondition.getFinishAmount()).compareTo(contractPayment.getPayAmount()) < 0) {
                return Result.error("amount-is-too-big", "本次付款金额大于未付款额，不能提交");
            }
        }
        BigDecimal allPayAmount = this.contractConditionService.getAllPayAmountByConditionId(contractCondition.getConditionId());
        if (allPayAmount.compareTo(contractCondition.getConditionAmount()) >= 0) {
            return Result.error("amount-is-too-big", "所有已付款及审核中，审核失败的付款总额已超出应付总额，不能提交");
        }
        if (allPayAmount.add(contractPayment.getPayAmount()).compareTo(contractCondition.getConditionAmount()) > 0) {
            return Result.error("amount-is-too-big", "本次付款金额大于未付款额，不能提交");
        }
        User user = LoginUtils.getCurrentUserInfo();
        contractPayment.setCreateUserId(user.getUserid());
        contractPayment.setCreateUserName(user.getUsername());
        contractPayment.setCreateDate(new Date());
        contractPayment.setBranchId(user.getBranchId());
        contractPaymentService.add(contractPayment);

        return Result.ok("add-ok", "添加成功！").setData(contractPayment);
    }

    @ApiOperation(value = "ht_contract_payment-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delContractPayment(@RequestBody ContractPayment contractPayment) {
        ContractPayment contractPaymentDb = this.contractPaymentService.selectOneObject(new ContractPayment(contractPayment.getId()));
        if ("1".equals(contractPaymentDb.getPayStatus())) {
            return Result.error("pay-status-is-finish", "已完成付款，不能删除");
        }
        if ("1".equals(contractPaymentDb.getBizFlowState())) {
            return Result.error("BizFlowState-is-1", "审批中，不能删除");
        }
        contractPaymentService.deleteByPk(contractPayment);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "ht_contract_payment-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractPayment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editContractPayment(@RequestBody ContractPaymentVo contractPayment) {
        ContractPayment contractPaymentDb = this.contractPaymentService.selectOneObject(new ContractPayment(contractPayment.getId()));
        if ("1".equals(contractPaymentDb.getPayStatus())) {
            return Result.error("pay-status-is-finish", "已完成付款，不能再修改");
        }
        if ("1".equals(contractPaymentDb.getBizFlowState())) {
            return Result.error("BizFlowState-is-1", "审批中，不能修改");
        }
        ContractCondition contractCondition = new ContractCondition(contractPayment.getConditionId());
        contractCondition = this.contractConditionService.selectOneObject(contractCondition);
        if (contractCondition == null) {
            return Result.error("condition-not-exists", "款项不存在");
        } else {
            if (contractCondition.getFinishAmount() == null) {
                contractCondition.setFinishAmount(BigDecimal.ZERO);
            }
            if ("2".equals(contractCondition.getConditionStatus())) {
                return Result.error("all-is-finish", "所有应付金额已完成，不能再付款");
            }
            if (contractCondition.getConditionAmount().compareTo(contractCondition.getFinishAmount()) <= 0) {
                return Result.error("all-is-finish", "所有应付金额已完成，不能再付款");
            }
            if (contractCondition.getConditionAmount().subtract(contractCondition.getFinishAmount()).compareTo(contractPayment.getPayAmount()) < 0) {
                return Result.error("amount-is-too-big", "本次付款金额大于未付款额，不能提交");
            }
        }
        BigDecimal allPayAmount = this.contractConditionService.getAllPayAmountByConditionId(contractCondition.getConditionId());
        allPayAmount = allPayAmount.subtract(contractPaymentDb.getPayAmount()).add(contractPaymentDb.getPayAmount());
        if (allPayAmount.compareTo(contractCondition.getConditionAmount()) > 0) {
            return Result.error("amount-is-too-big", "所有已付款及审核中，审核失败的付款总额已超出应付总额，不能提交");
        }
        contractPayment.setPayStatus(contractPaymentDb.getPayStatus());
        contractPayment.setBizFlowState(contractPaymentDb.getBizFlowState());
        contractPaymentService.editContractPayment(contractPayment);

        return Result.ok("edit-ok", "修改成功！").setData(contractPayment);
    }

    @ApiOperation(value = "ht_contract_payment-批量修改某些字段", notes = "")
    @ApiEntityParams(value = ContractPayment.class, props = {}, remark = "ht_contract_payment", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = ContractPayment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        contractPaymentService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "付款关联发票", notes = " ")
    @ApiResponses({
            @ApiResponse(code = 200, response = ContractPaymentInvoice.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value = "/linkInvoices", method = RequestMethod.POST)
    public Result paymentLinkInvoices(@RequestBody PaymentLinkInvoicesVo linkInvoices) {


        this.contractPaymentInvoiceService.paymentLinkInvoices(linkInvoices);

        return Result.ok("update-ok", "成功更新一条数据");
    }

    //@AuditLog(firstMenu="合同管理",secondMenu="付款管理",func="processApprova",funcDesc="付款审批",operType= OperType.UPDATE)
    @RequestMapping(value = "/processApprova", method = RequestMethod.POST)
    public Result processApprova(@RequestBody Map<String, Object> flowVars) {
        this.contractPaymentService.processApprova(flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));
        return Result.ok("", "成功提交审批");
    }


    @ApiOperation(value = "ht_contract_payment-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelContractPayment(@RequestBody List<ContractPayment> contractPayments) {
        User user = LoginUtils.getCurrentUserInfo();
        if (contractPayments.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<ContractPayment> datasDb = contractPaymentService.listByIds(contractPayments.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<ContractPayment> can = new ArrayList<>();
        List<ContractPayment> no = new ArrayList<>();
        for (ContractPayment data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            contractPaymentService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "ht_contract_payment-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = ContractPayment.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(ContractPayment contractPayment) {
        ContractPayment data = (ContractPayment) contractPaymentService.getById(contractPayment);
        return Result.ok().setData(data);
    }

}
